package com.imonsoft.sqm.web.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.imonsoft.common.constant.CCommon;
import com.imonsoft.common.constant.ConstantDict;
import com.imonsoft.common.constant.ConstantSqm;
import com.imonsoft.common.exception.SystemException;
import com.imonsoft.common.httpModel.DataGrid;
import com.imonsoft.common.httpModel.Pager;
import com.imonsoft.common.httpModel.ReturnMessage;
import com.imonsoft.common.httpModel.TreeGridNode;
import com.imonsoft.common.util.AjaxUtil;
import com.imonsoft.common.util.JsonUtil;
import com.imonsoft.sqm.pojo.basedata.Dictionary;
import com.imonsoft.sqm.pojo.sys.Function;
import com.imonsoft.sqm.pojo.sys.Role;
import com.imonsoft.sqm.pojo.sys.User;
import com.imonsoft.sqm.service.basedata.DictionaryService;
import com.imonsoft.sqm.service.sys.FunctionService;
import com.imonsoft.sqm.service.sys.UserService;
import com.imonsoft.sqm.validator.sys.UserValidator;
import com.imonsoft.sqm.vo.sys.UserUntil;

@Controller
@RequestMapping("/sys/user")
public class UserController {
	protected final Log logger = LogFactory.getLog(getClass());
	@Autowired
	private UserService userService;
	@Autowired
	private UserValidator userValidator;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private FunctionService functionService;

	@RequestMapping("/listUI.do")
	public void listUI(ModelMap model) {
		List<Dictionary> dictBaseDataStatusList = dictionaryService.findDictionaryByType(ConstantDict.BASE_DATA_STATUS);
		model.put("dictBaseDataStatusList", dictBaseDataStatusList);
	}

	@RequestMapping(value = "/ajaxList.do", method = RequestMethod.POST)
	public void ajaxList(HttpServletResponse response, Pager pager, User user) {
		DataGrid<User> dataGrid = new DataGrid<User>();
		try {
			dataGrid = userService.getDataGrid(user, pager);
		} catch (SystemException se) {
			logger.info(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		AjaxUtil.renderJSON(response, JsonUtil.bean2json(dataGrid));
	}

	@RequestMapping("/addUI.do")
	public void addUI(ModelMap model) {
	}

	@RequestMapping(value = "/ajaxAdd.do", method = RequestMethod.POST)
	public void ajaxAdd(HttpServletResponse response, UserUntil userVo, BindingResult result) {
		ReturnMessage message = new ReturnMessage();
		try {
			userValidator.methodAddValidate(userVo, result);
			if (result.hasErrors()) {
				message.setObj(userValidator.getErrors(result));
			} else {
				User user = (User) userVo;
				userService.insert(user);
				message.setSuccess(true);
				message.setMsg(ConstantSqm.OPERATE_SUCCESS);
			}
		} catch (SystemException se) {
			logger.info(se.getMessage());
			message.setMsg(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
			message.setMsg(CCommon.EXCEPTION_MSG);
		}
		AjaxUtil.renderJSON(response, JsonUtil.bean2json(message));
	}

	@RequestMapping(value = "/modifyUI.do")
	public void modifyUI(ModelMap model, Long id) {
		if (null != id) {
			User user = userService.get(id);
			model.put("user", user);
		} else {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
	}

	@RequestMapping(value = "/modeifyRoleUI.do")
	public void modeifyRoleUI(ModelMap model, Long id) {
		if (null != id) {
			User user = userService.get(id);
			List<Role> roles = userService.getRoleListByUserId(id);
			String ids = "";
			if (roles != null) {
				for (Role role : roles) {
					ids += role.getId() + ",";
				}
			}
			ids = ids.substring(0, ids.length() - 1);
			model.put("ids", ids);
			model.put("user", user);
		} else {
			throw new SystemException(ConstantSqm.DATA_ERROR);
		}
	}

	@RequestMapping(value = "/ajaxModify.do", method = RequestMethod.POST)
	public void ajaxModify(HttpServletResponse response, User user, BindingResult result) {
		ReturnMessage message = new ReturnMessage();
		try {
			userValidator.methodModifyValidate(user, result);
			if (result.hasErrors()) {
				message.setObj(userValidator.getErrors(result));
			} else {
				userService.update(user);
				message.setSuccess(true);
				message.setMsg(ConstantSqm.OPERATE_SUCCESS);
			}

		} catch (SystemException se) {
			logger.info(se.getMessage());
			message.setMsg(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
			message.setMsg(CCommon.EXCEPTION_MSG);
		}
		AjaxUtil.renderJSON(response, JsonUtil.bean2json(message));
	}

	@RequestMapping(value = "/ajaxDelete.do", method = RequestMethod.POST)
	public void ajaxDelete(HttpServletResponse response, String[] ids) {
		ReturnMessage message = new ReturnMessage();
		try {
			List<Long> idList = new ArrayList<Long>();
			for (String id : ids) {
				idList.add(Long.valueOf(id));
			}
			userService.deleteUser(idList);
			message.setSuccess(true);
			message.setMsg(ConstantSqm.OPERATE_SUCCESS);
		} catch (SystemException se) {
			logger.info(se.getMessage());
			message.setMsg(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
			message.setMsg(CCommon.EXCEPTION_MSG);
		}
		AjaxUtil.renderJSON(response, JsonUtil.bean2json(message));
	}

	@RequestMapping(value = "/ajaxTreeGrid.do", method = RequestMethod.POST)
	public void ajaxTreeGrid(HttpServletResponse response, Function function, boolean isClose) {
		List<TreeGridNode> treeList = new ArrayList<TreeGridNode>();
		try {
			List<Function> functionList = UserUntil.getUser().getFunctionList();
			List<TreeGridNode> tempList = new ArrayList<TreeGridNode>();
			if (functionList != null) {
				for (Function functionTemp : functionList) {
					TreeGridNode node = functionTemp.createTreeGridNode();
					if (isClose) {
						node.setState("closed");
					}
					Map<String, String> map = new HashMap<String, String>();
					map.put("url", node.getUrl());
					map.put("id", node.getId());
					node.setAttributes(map);
					tempList.add(node);
				}
			}
			treeList = TreeGridNode.getTreeGridNodeList(tempList);
		} catch (SystemException se) {
			logger.debug(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
		}
		AjaxUtil.renderJSON(response, JsonUtil.bean2json(treeList));
	}

	@RequestMapping(value = "/ajaxSetUserRoles.do", method = RequestMethod.POST)
	public void ajaxSetUserRoles(HttpServletResponse response, User user, @RequestParam("list") List<Long> roleList) {
		ReturnMessage message = new ReturnMessage();
		try {
			userService.txSetUserRoles(user, roleList);
			message.setSuccess(true);
			message.setMsg(ConstantSqm.OPERATE_SUCCESS);
		} catch (SystemException se) {
			logger.info(se.getMessage());
			message.setMsg(se.getMessage());
		} catch (Exception e) {
			logger.error(e.getMessage());
			message.setMsg(CCommon.EXCEPTION_MSG);
		}
		AjaxUtil.renderJSON(response, JsonUtil.bean2json(message));
	}
}
